import relationalStore from '@ohos.data.relationalStore';
import emitter from '@ohos.events.emitter'
import dayjs from 'dayjs'
// import * as isLeapYear from 'dayjs/plugin/isLeapYear' // 导入插件
import relativeTime from "dayjs/plugin/relativeTime"
import 'dayjs/locale/zh-cn' // 导入本地化语言

// dayjs.extend(isLeapYear) // 使用插件
dayjs.locale('zh-cn') // 使用本地化语言


const STORE_CONFIG = {
  name: 'MyData.db', // 数据库文件名
  securityLevel: relationalStore.SecurityLevel.S2 // 数据库安全级别
};
dayjs.extend(relativeTime)
export function dateFormat(date: Date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  return `${year}-${month}-${day}`
}
export function getDaysBetween(date2){
  var now=dayjs()
  var endDate = dayjs(date2)
  return endDate.from(now)
}
//返回地图图片
export function getMapImage(lng:number,lat:number){
  let ak="Ir7z3sSO2Lhwg0AprFzCzWd1VWP2Y9kZ"
  let placePoint=lng.toString()+','+lat.toString()
  let url=`https://api.map.baidu.com/staticimage/v2?ak=${ak}&width=280&height=140&zoom=11&scale=2&center=${placePoint}&markers=${placePoint}`
  return url
}
export function initDatabase(context,callback) {
  const SQL_CREATE_TABLE = `CREATE TABLE TravelRecords (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  destination TEXT NOT NULL,
  travel_date TEXT,
  transportation TEXT,
  latitude REAL,
  longitude REAL,
  budget REAL,
  note Text,
  isDone INTEGER,
  expense REAL
)`; // 建表Sql语句

  relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
    if (err) {
      console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
      return;
    }
    console.info(`Succeeded in getting RdbStore.`);
    store.executeSql(SQL_CREATE_TABLE).then(()=>{
      // 设置分布式同步表。
      store.setDistributedTables(['TravelRecords']);
      let valueBuckets= [
        {
          "destination": "武汉市武昌区湖北大学(武昌主校区)",
          "travel_date": "2023-10-09",
          "transportation": "飞机",
          "latitude": 30.584492301645774,
          "longitude": 114.34012081061486,
          "budget": 1500.00,
          "note":"可能有沙尘暴",
          "isDone":1,
          "expense":20
        },
        {
          "destination": "武汉市武昌区东湖生态旅游风景区",
          "travel_date": "2023-10-15",
          "transportation": "公共交通",
          "latitude": 30.557868805169253,
          "longitude": 114.42000496368398,
          "budget": 2000.50,
          "note":"有点冷",
          "isDone":1,
          "expense":0
        },
        {
          "destination": "杭州市西湖区西湖风景区",
          "travel_date": "2023-10-25",
          "transportation": "飞机,骑行",
          "latitude": 30.228932114135855,
          "longitude": 120.12792000971587,
          "budget": 1000.75,
          "note":"太热了",
          "isDone":1,
          "expense":0
        }
      ]
      store.batchInsert("TravelRecords",valueBuckets).then((insertNum)=>{
        syncData("TravelRecords",store)
        console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
        queryRecords(context).then((res)=>{
          console.log(JSON.stringify(res)+"___________")
        })
        callback()

      })
    }); // 创建数据表

    // 这里执行数据库的增、删、改、查等操作

  });
}
export function queryRecords(context,resultColumns=[],last=0){
  return new Promise((resolve,reject)=>{
    let predicates = new relationalStore.RdbPredicates("TravelRecords").orderByDesc("id");
    if(last){
      //如果设置了最近几条记录
      predicates.limitAs(last)
    }
    relationalStore.getRdbStore(context,STORE_CONFIG).then((store)=>{
      store.query(predicates, resultColumns, function (err, resultSet) {
        if (err) {
          console.error(`Query failed, code is ${err.code},message is ${err.message}`);
          reject(err)
          return;

        }
        console.info(`ResultSet column names: ${resultSet.columnNames}`);
        console.info(`ResultSet column count: ${resultSet.columnCount}`);
        let results=[]

        //这一步是必要的,否则取不到数据,将指针指向第一个数据
        resultSet.goToFirstRow();
        if(resultColumns.length==0){
          //默认返回全部
          //读取全部数据
          while(!resultSet.isEnded){
            let id=resultSet.getDouble(resultSet.getColumnIndex("id"))
            let destination=resultSet.getString(resultSet.getColumnIndex("destination"))
            let travel_date=resultSet.getString(resultSet.getColumnIndex("travel_date"))
            let transportation=resultSet.getString(resultSet.getColumnIndex("transportation"))
            //经纬度只能通过getDouble获取，因为它们的长度越界了
            let latitude=resultSet.getDouble(resultSet.getColumnIndex("latitude"))
            let longitude=resultSet.getDouble(resultSet.getColumnIndex("longitude"))
            let budget=resultSet.getDouble(resultSet.getColumnIndex("budget"))
            let note=resultSet.getString(resultSet.getColumnIndex("note"))
            let isDone=resultSet.getDouble(resultSet.getColumnIndex("isDone"))
            let expense=resultSet.getDouble(resultSet.getColumnIndex("expense"))
            results.push({id,destination,travel_date,transportation,latitude,longitude,budget,note,isDone,expense})
            resultSet.goToNextRow()
          }
          resolve(results)
        }
        resolve(results)
        resultSet.close()
      })
    })
  })
}
export function queryAsId(context,id,resultColumns=[]){
  return new Promise((resolve,reject)=>{
    let predicates = new relationalStore.RdbPredicates("TravelRecords");
    predicates.equalTo("id",id)
    relationalStore.getRdbStore(context,STORE_CONFIG).then((store)=>{
      store.query(predicates, resultColumns, function (err, resultSet) {
        if (err) {
          console.error(`Query failed, code is ${err.code},message is ${err.message}`);
          reject(err)
          return;
        }
        console.info(`ResultSet column names: ${resultSet.columnNames}`);
        console.info(`ResultSet column count: ${resultSet.columnCount}`);
        let results=[]

        //这一步是必要的,否则取不到数据,将指针指向第一个数据
        resultSet.goToFirstRow();
        if(resultColumns.length==0){
          //默认返回全部
          //读取全部数据
          while(!resultSet.isEnded){
            let id=resultSet.getDouble(resultSet.getColumnIndex("id"))
            let destination=resultSet.getString(resultSet.getColumnIndex("destination"))
            let travel_date=resultSet.getString(resultSet.getColumnIndex("travel_date"))
            let transportation=resultSet.getString(resultSet.getColumnIndex("transportation"))
            let latitude=resultSet.getDouble(resultSet.getColumnIndex("latitude"))
            let longitude=resultSet.getDouble(resultSet.getColumnIndex("longitude"))
            let budget=resultSet.getDouble(resultSet.getColumnIndex("budget"))
            let note=resultSet.getString(resultSet.getColumnIndex("note"))
            let isDone=resultSet.getDouble(resultSet.getColumnIndex("isDone"))
            let expense=resultSet.getDouble(resultSet.getColumnIndex("expense"))
            results.push({id,destination,travel_date,transportation,latitude,longitude,budget,note,isDone,expense})
            resultSet.goToNextRow()
          }
          resolve(results)
        }
        resolve(results)
        resultSet.close()
      })
    })
  })
}
export function queryAsOther(context,predicates:relationalStore.RdbPredicates,resultColumns=[]){
  return new Promise((resolve,reject)=>{
    relationalStore.getRdbStore(context,STORE_CONFIG).then((store)=>{
      store.query(predicates, resultColumns, function (err, resultSet) {
        if (err) {
          console.error(`Query failed, code is ${err.code},message is ${err.message}`);
          reject(err)
          return;
        }
        console.info(`ResultSet column names: ${resultSet.columnNames}`);
        console.info(`ResultSet column count: ${resultSet.columnCount}`);
        let results=[]

        //这一步是必要的,否则取不到数据,将指针指向第一个数据
        resultSet.goToFirstRow();
        if(resultColumns.length==0){
          //默认返回全部
          //读取全部数据
          while(!resultSet.isEnded){
            let id=resultSet.getDouble(resultSet.getColumnIndex("id"))
            let destination=resultSet.getString(resultSet.getColumnIndex("destination"))
            let travel_date=resultSet.getString(resultSet.getColumnIndex("travel_date"))
            let transportation=resultSet.getString(resultSet.getColumnIndex("transportation"))
            let latitude=resultSet.getDouble(resultSet.getColumnIndex("latitude"))
            let longitude=resultSet.getDouble(resultSet.getColumnIndex("longitude"))
            let budget=resultSet.getDouble(resultSet.getColumnIndex("budget"))
            let note=resultSet.getString(resultSet.getColumnIndex("note"))
            let isDone=resultSet.getDouble(resultSet.getColumnIndex("isDone"))
            let expense=resultSet.getDouble(resultSet.getColumnIndex("expense"))
            results.push({id,destination,travel_date,transportation,latitude,longitude,budget,note,isDone,expense})
            resultSet.goToNextRow()
          }
          resolve(results)
        }
        resolve(results)
        resultSet.close()
      })
    })
  })
}
export function insertRecords(context,valueBucket){
  return new Promise((resolve,reject)=>{
    relationalStore.getRdbStore(context,STORE_CONFIG).then((store)=>{
      store.insert("TravelRecords",valueBucket).then((rowId)=>{
        syncData("TravelRecords",store)
        resolve(rowId)
        emitter.emit({eventId:1})
      }).catch((err)=>{
        reject(err)
      })
    })
  })

}
export function updateRecordAsId(context,id,valueBucket){
  return new Promise((resolve,reject)=>{
    let predicates = new relationalStore.RdbPredicates("TravelRecords");
    predicates.equalTo("id",id)
    relationalStore.getRdbStore(context,STORE_CONFIG).then((store)=>{
      store.update(valueBucket,predicates).then((rows)=>{
        syncData("TravelRecords",store)
        console.info(`Updated row count: ${rows}`);
        emitter.emit({eventId:1})
        resolve(rows)
      })
    })
  })
}
export function deleteRecordAsId(context,id){
  return new Promise((resolve,reject)=>{
    let predicates = new relationalStore.RdbPredicates("TravelRecords");
    predicates.equalTo("id",id)
    relationalStore.getRdbStore(context,STORE_CONFIG).then((store)=>{
     store.delete(predicates).then((rows)=>{
       syncData("TravelRecords",store)
       console.info(`delete row count: ${rows}`);
       emitter.emit({eventId:1})
       resolve(rows)
     })
    })
  })
}
//同步分布式数据
function syncData(table:string,store){
  // 构造用于同步分布式表的谓词对象
  let predicates = new relationalStore.RdbPredicates(table);
  // 调用同步数据的接口
  store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => {
    // 判断数据同步是否成功
    if (err) {
      console.error(`Failed to sync data. Code:${err.code},message:${err.message}`);
      return;
    }
    console.info('Succeeded in syncing data.');
    for (let i = 0; i < result.length; i++) {
      console.info(`device:${result[i][0]},status:${result[i][1]}`);
    }
  })

}